package com.ruoyi.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    public static String doPostByForm(String url, Map<String,String> paramMap) throws IOException {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;

        httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 创建表单数据
        List<NameValuePair> form = new ArrayList<>();
        for (Map.Entry<String,String> entry:paramMap.entrySet()){
            form.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 创建表单实体
        httpPost.setEntity(new UrlEncodedFormEntity(form));
        // 设置请求实体
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String responseContent = EntityUtils.toString(entity);
            System.out.println(responseContent);
            response.close();
            httpClient.close();
            return responseContent;
        }else{
            response.close();
            httpClient.close();
            return null;
        }



    }
}
